<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/09/03
 * Time: 14:58
 */

namespace business\datacenter\services;

use business\datacenter\repositories\SupplierBasicRepository;
use business\datacenter\repositories\SupplierRecruitRepository;
use business\datacenter\repositories\SupplierServiceCategoryRepository;
use business\datacenter\repositories\SupplierTenderingRepository;
use business\elasticsearch\repositories\SupplierBasicRepository as EsSupplierBasicRepository;
use common\utils\DateTimeUtils;

class SupplierBasicCronService
{
    /**
     * 处理平台供应商数据同步到es
     * @param int $type
     * @param int $isCreateIndex
     * @param int $page
     */
    public function processSupplierBasicRsyncToEs($type = 1, $isCreateIndex = 1, $page = 0)
    {
        set_time_limit(0);
        $supplierBasicRepository = new SupplierBasicRepository();
        $condition      = [];
        $microSecond    = 50 * 1000;
        $num            = 1;
        $size           = 100;

        // 关闭增量同步，每次执行全量
        $closeCronRecord = true;

        if (!empty($page)) {
            $num = $page;
        }

        $pointOfTime = $supplierBasicRepository
            ->getSupplierBasicOne(
                $condition, 'last_updated_time', ['last_updated_time' => SORT_ASC])['last_updated_time'];

        $platformDataRsyncToEsCronRecord = $supplierBasicRepository
            ->getPlatformDataRsyncToEsCronRecord(['type_id' => $type]);

        if (!empty($platformDataRsyncToEsCronRecord)) {
            $starTime = $platformDataRsyncToEsCronRecord['end_time'];
        } else {
            if ($isCreateIndex == 1) {
                // 初始化创建索引
                echo '正在创建索引...' . PHP_EOL;
                (new EsSupplierBasicRepository())->createSupplierBasicIndex();
                echo '索引创建成功...' . PHP_EOL;
            }
            $starTime = $pointOfTime;
        }

        $endTime = date('Y-m-d H:i:s', DateTimeUtils::time());

        !$closeCronRecord && $supplierBasicRepository->storePlatformDataRsyncToEsCronRecord(
            ['type_id' => $type, 'start_time' => $starTime, 'end_time' => $endTime]);

        echo '正在同步数据...' . PHP_EOL;

        do {
            $list = $this->getSupplierBasicList($starTime, $endTime, $num, $size);
            if (!empty($list)) {
                $this->rsyncSupplierBasicToEs($list, $starTime, $endTime, $num, $size);
                $num++;
                usleep($microSecond);
            } else {
                $num = 1;
                break;
            }
        } while (true);
    }

    /**
     * 返回平台供应商数据列表
     * @param $starTime
     * @param $endTime
     * @param $page
     * @param $size
     * @return array
     * @throws \yii\db\Exception
     */
    public function getSupplierBasicList($starTime, $endTime, $page, $size)
    {
        $supplierBasicRepository           = new SupplierBasicRepository();
        $supplierServiceCategoryRepository = new SupplierServiceCategoryRepository();
        $supplierRecruitRepository         = new SupplierRecruitRepository();
        $supplierTenderingRepository       = new SupplierTenderingRepository();

        $offset = ($page - 1) * $size;

        echo implode('|', [$page, $offset, $starTime, $endTime]) . PHP_EOL;

        $data = $supplierBasicRepository->getSupplierBasicList([], $starTime, $endTime, '*', $offset, $size);

        if (!empty($data)) {
            foreach ($data as & $item) {
                $item['service_category'] = $supplierServiceCategoryRepository
                    ->getSupplierServiceCategoryListBySupplierId($item['supplier_id']);

                $item['recruit_item']     = $supplierRecruitRepository
                    ->getRecruitItemBySupplierId($item['supplier_id']);

                $item['tendering_item']   = $supplierTenderingRepository
                    ->getSupplierAnnouncementsItemBySupplierId($item['supplier_id']);
            }
        }

        return $data;
    }

    /**
     * 平台供应商数据同步到es中
     * @param array $data
     * @return array
     */
    public function rsyncSupplierBasicToEs(
        $data = [],
        $starTime = '',
        $endTime = '',
        $page = 0,
        $size = 0
    ) {
        if (!empty($data)) {
            foreach ($data as $value) {
                $result = var_export($value, true) . PHP_EOL;
                try {
                    (new EsSupplierBasicRepository())->saveSupplierBasicRecord($value, $value['supplier_id']);
                } catch (\Exception $ex) {
                    (new SupplierBasicRepository())->storePlatformDataRsyncToEsErrorLog([
                        'type_id'       => 1,
                        'error_message' => var_export(['page' => $page, 'size' => $size, 'info' => $result], true),
                        'start_time'    => $starTime,
                        'end_time'      => $endTime,
                        'created_time'  => DateTimeUtils::now()
                    ]);
                }
            }
        }

        return [];
    }
}
